package com.e_manager.soft.emanager.controller;

import com.e_manager.soft.emanager.annotation.BaseController;
import com.e_manager.soft.emanager.entity.User;
import com.e_manager.soft.emanager.resultMsg.ResultConstant;
import com.e_manager.soft.emanager.resultMsg.ResultInfo;
import com.e_manager.soft.emanager.service.TokenManager;
import com.e_manager.soft.emanager.service.UserService;
import com.e_manager.soft.emanager.token.TokenModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author : lip[lip4051@163.com]
 * @create : 2018/3/14 0014 上午 11:17
 */
@BaseController
public class LoginController {
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录", notes = "根据url的id来获取用户详细信息")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultInfo<TokenModel> login(@RequestBody User user) {
        Assert.notNull(user.getLoginName(), "username can not be empty");
        Assert.notNull(user.getLoginPwd(), "password can not be empty");
        TokenModel token = new TokenModel();
        User u = userService.getByUserName(user.getLoginName());
        ResultInfo resultInfo = new ResultInfo();
        if (u == null || u.getDeleteFlag() == "1") {
            resultInfo.setMsg(ResultConstant.USER_NOT_FOUND.getMessage());
            resultInfo.setCode(ResultConstant.USER_NOT_FOUND.getCode());
            return resultInfo;
        }
        if (!u.getLoginPwd().equals(user.getLoginPwd())) {
            resultInfo.setMsg(ResultConstant.USERNAME_OR_PASSWORD_ERROR.getMessage());
            resultInfo.setCode(ResultConstant.USERNAME_OR_PASSWORD_ERROR.getCode());
            return resultInfo;
        }
        if (user.getXinToken() != null && !user.getXinToken().equals("")) {
            u.setXinToken(user.getXinToken());
            u.setXinDev(user.getXinDev());
        }
        token = tokenManager.createToken(u);
        return new ResultInfo(token);
    }
}
